import request from "./request";
import store from "../store/index";
import {iLocal, iSession} from "./cache.js";
const Tool = {}

/**
 * 将一个数字格式化为一个金钱格式的数组，补充后两个小数点
 * @param number
 */
Tool.toMoneyFormat = function(number){
    let f = parseFloat(number);
    if (isNaN(f)) {
        return false;
    }
    f = Math.round(number*100)/100;
    let s = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

/**
 * 当前用户是否关注公众号
 */
Tool.testAttention = function(){
    return new Promise((success)=>{
        request("weChat/testAttention")
            .then((res)=>{
                if(res.data.status === "success"){
                    success(res.data.data);
                }
            });
    });
}

/**
 * 获取公众号关注二维码
 */
Tool.getWxAttentionQrcode = function(){
    return new Promise((success)=>{
        request("weChat/getWxAttentionQrcode")
            .then((res)=>{
                if(res.data.status === "success"){
                    success(res.data.data);
                }
            });
    });
}

/**
 * 定位，获取用户所在城市，省，市，区
 */
Tool.location = function(){
    return new Promise((success)=>{
        if(store.state.area.length <= 0){
            let cacheArea = iLocal.get("area");
            if(!cacheArea){
                this.getLnglat()
                    .then((lnglat)=>{
                        let geocoder = new window.AMap.Geocoder();
                        geocoder.getAddress(lnglat,(status,result)=>{
                            if(status === 'complete'){
                                let address = result.regeocode.addressComponent;
                                let area = [address.province,address.city,address.district];
                                iLocal.set("area",area);
                                store.commit("setArea",area);
                                success(area);
                            }
                        });
                    })
                    .catch(() => {
                        let area;
                        if(process.env.NODE_ENV === 'development')
                             area = ['山西省','临汾市','尧都区'];
                            iLocal.set("area",area);
                            store.commit("setArea",area);
                            success(area);
                    });
            }else{
                store.commit("setArea",cacheArea);
                success(cacheArea);
            }
        }else{
            success(store.state.area);
        }
    });
}

/**
 * 获取用户经纬度
 * @returns {Promise<unknown>}
 */
Tool.getLnglat = function(){
    return new Promise((success,error)=>{
        if(process.env.NODE_ENV === 'development'){
            let Location = new window.AMap.Geolocation();
            Location.getCurrentPosition((status,result)=>{
                if(status === 'complete'){
                    success([result.position.lng,result.position.lat]);
                }else{
                    error(result);
                }
            });
        }else{
            window.wx.ready(()=>{
                window.wx.getLocation({
                    success:(res)=>{
                        success([res.longitude,res.latitude]);
                    }
                });
            });
        }
    })
}


/**
 * 获取系统所需参数
 */
Tool.getSetting = function(){
    return new Promise((success)=>{
        if(store.state.setting.length <= 0){
            request("setting/easyFind",{
                return:["publish_red","attention_publish","coerce_phone","open_phone"]
            })
                .then((res)=>{
                    if(res.data.status === "success"){
                        store.commit("setSetting",res.data.data);
                        success(res.data.data);
                    }
                });
        }else{
            success(store.state.setting);
        }
    });
}

/**
 * 登录获取用户uid
 */
Tool.login = function(){
    return new Promise((success) =>{
        let uid = iSession.get('kuyuan_red_uid')
        if ((uid || uid === undefined) && process.env.NODE_ENV === 'production') {
            store.commit("setUid",uid)
            success(uid)
        } else {
            request('member/login')
                .then((res) => {
                    if(process.env.NODE_ENV === 'development') window.console.log('服务器登录返回uid')
                    iSession.set('kuyuan_red_uid',res.data.data)
                    store.commit("setUid",res.data.data)
                    success(res.data.data)
                })
        }
    })
}

/**
 * 获取解析分享数据uid和red_id
 */
Tool.parseShareId = function(){
    return new Promise((success) => {
        request('share/find', {
            share_id: window.sysinfo.share_id
        })
            .then((res)=>{
                let {status, data} = res.data
                if(status === 'success'){
                    store.commit('setShare', {
                        uid: parseInt(data.uid),
                        red_id: parseInt(data.red_id)
                    })
                    success('success')
                } else {
                    success('error')
                }
            })
    })
}


export default Tool;
